<?php

namespace App\Http\Controllers\Entity\Asset\Video;

use App\Admin\Extensions\Tools\GridView;
use App\Http\Controllers\Controller;
use App\Http\Requests\Entity\Asset\Video\VserialiRequest;
use App\Jobs\Injection\VserialiInjectionJob;
use App\Jobs\Publish\VserialiJob;
use App\Models\Entity\Asset\Video\Media\Vifile;
use App\Models\Entity\Asset\Video\Media\Vposteri;
use App\Models\Entity\Asset\Video\Vasseti;
use App\Models\Entity\Asset\Video\Vseriali;
use App\Models\Injection\InjectVserialiHistory;
use App\Models\Task\Task;
use App\Models\Entity\content_audit\content_audit;
use App\Repositories\Entity\Asset\Video\VserialiRepository;
use Encore\Admin\Controllers\ModelForm;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Form;
use Encore\Admin\Grid;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Tab;
use Flash;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Input;
use Illuminate\Support\Facades\Route;
use Response;
use Validator;
use App\Classes\Injection\VserialiInjection;
use App\Classes\Publish\Publication;

class VserialiController extends Controller
{
    use ModelForm;

    /** @var  VserialiRepository */
    private $vserialiRepository;

    public function __construct(VserialiRepository $vserialiRepo)
    {
        $this->vserialiRepository = $vserialiRepo;
    }

    /**
     * Display a listing of the Vseriali.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        Admin::script('injectVseriali();');
        return Admin::content(function (Content $content) use ($request) {

            $content->header(__('entity.asset.video.vserialis.index_header'));


            switch ($request->get('view')){
                case 'editor':
                {
                    $content->description('编辑审核申请');
                    $content->body($this->editor_grid($request));
                    break;
                }
                case 'online':
                {
                    $content->description('上线申请');
                    $content->body($this->online_grid($request));
                    break;
                }
                case 'publish':
                {
                    $content->description('发布申请');
                    $content->body($this->publish_grid($request));
                    break;
                }
                case 'offline':
                {
                    $content->description('下线申请');
                    $content->body($this->offline_grid($request));
                    break;
                }
                default:
                    $content->description(__('entity.asset.video.vserialis.index_description'));
                    $content->body($this->grid($request));
                    $content->row(view('entity.tag.addContentTagModal'));
                    break;
            }


        });
    }

    /**
     * Show the form for creating a new Vseriali.
     *
     * @return Response
     */
    public function create()
    {
        return Admin::content(function (Content $content) {

            $content->header(__('entity.asset.video.vserialis.create_header'));
            $content->description(__('entity.asset.video.vserialis.create_description'));

            $content->body($this->form());

        });
    }

    /**
     * Store a newly created Vseriali in storage.
     *
     * @param VserialiRequest $request
     *
     * @return Response
     */
    public function store(VserialiRequest $request)
    {
        $input = $request->all();

        $vseriali = $this->vserialiRepository->create($input);
        if ($vseriali) {
            if (is_array($request->get('vposteris'))) {
                $vseriali->vposteris()->sync(array_filter($request->get('vposteris')));
            }
            if (is_array($request->get('vifiles'))) {
                $vseriali->vifiles()->sync(array_filter($request->get('vifiles')));
            }
        }

        Flash::success(__('entity.asset.video.vserialis.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.asset.video.vserialis.index'));

    }

    /**
     * Display the specified Vseriali.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        $vseriali = $this->vserialiRepository->findWithoutFail($id);

        if (empty($vseriali)) {
            Flash::error(__('entity.asset.video.vserialis.not_found'));

            return redirect(route('entity.asset.video.vserialis.index'));
        }

        return view('entity.asset.video.vserialis.show')->with('vseriali', $vseriali);

    }

    /**
     * Show the form for editing the specified Vseriali.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('entity.asset.video.vserialis.edit_header'));
            $content->description(__('entity.asset.video.vserialis.edit_description'));

            $content->body($this->form()->edit($id));
        });
    }

    /**
     * Update the specified Vseriali in storage.
     *
     * @param  int              $id
     * @param VserialiRequest $request
     *
     * @return Response
     */
    public function update($id, Request $request)
    {
        $sValidators = [
            'vseriali_no' => 'required|unique:vserialis,vseriali_no,' . $id,
            'name'        => 'required|max:100',
            'title'       => 'max:100',
            'subtitle'    => 'max:100',
            'episode'     => 'required|numeric',
            'score'       => 'numeric',
            'vasseti_id'  => 'required',
            'firstdate'   => 'date',
            'online_at'   => 'date',
            'offline_at'  => 'date',
            'short_desc'  => 'required',
            'listorder'   => 'required|numeric',
        ];
        $validators = [];

        $input = $request->all();

        // 判断是否行内编辑,只有下线的可以编辑
        $status = Vseriali::where(['online_status' => 0, 'id' => $id])->first();
        if ($status) {
            $input = $this->handleEditable($input);
        }

        // 动态判断校验
        foreach ($input as $key => $value) {
            if (isset($sValidators[$key])) {
                $validators[$key] = $sValidators[$key];
            }
        }
        // 定义校验, 没有移到request
        $validator = Validator::make($input, $validators, [
            // 'required' => ':attribute 不能为空',
        ], [
            'vseriali_no' => '分集编号',
            'name'        => '名称',
            'title'       => '标题',
            'subtitle'    => '副标题',
            'episode'     => '第几集',
            'score'       => '评分',
            'vasseti_id'  => '剧集',
            'firstdate'   => '首播时间',
            'online_at'   => '上线时间',
            'offline_at'  => '下线时间',
            'short_desc'  => '描述',
        ]
        );

        // 校验
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $vseriali = $this->vserialiRepository->findWithoutFail($id);

        if (empty($vseriali)) {
            Flash::error(__('entity.asset.video.vserialis.not_found'));

            return redirect(route('entity.asset.video.vserialis.index'));
        }

        $vseriali = $this->vserialiRepository->update($input, $id);

        if ($vseriali) {
            if (is_array($request->get('vposteris'))) {
                $vseriali->vposteris()->sync(array_filter($request->get('vposteris')));
            }
            if (is_array($request->get('vifiles'))) {
                $vseriali->vifiles()->sync(array_filter($request->get('vifiles')));
            }
        }

        Flash::success(__('entity.asset.video.vserialis.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.asset.video.vserialis.index'));
    }

    /**
     * Remove the specified Vseriali from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        } else {
            // 只有下线且下线发布的才能删除
            $vseriali = Vseriali::where('id', $id)->where(['online_status' => 0, 'publish_down_status' => 1])->orWhere(['online_status' => 1, 'publish_status' => 0])->first();
            if(empty($vseriali)){
                return response()->json(['message' => '只有状态为下线且已下线发布或上线未发布的才可以删除', 'status' => false]);
            }
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            // 只有下线且下线发布的才能删除
            $id = Vseriali::whereIn('id', $id)->where(['online_status' => 0, 'publish_down_status' => 1])->orWhere(['online_status' => 1, 'publish_status' => 0])->pluck('id')->toArray();
            if ($flag = $this->vserialiRepository->batchDelete('id', $id)) {
                return response()->json(['message' => __('entity.asset.video.vserialis.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => '只有状态为下线发布的才可以删除', 'status' => $flag]);
            }
        }

        $vseriali = $this->vserialiRepository->findWithoutFail($id);

        if (empty($vseriali)) {
            Flash::error(__('entity.asset.video.vserialis.not_found'));

            return redirect(route('entity.asset.video.vserialis.index'));
        }

        if ($flag = $this->vserialiRepository->delete($id)) {
            // 删除图片
            $vseriali->vposteris()->detach();
            // 文件
            $vseriali->vifiles()->detach();
            return response()->json(['message' => __('entity.asset.video.vserialis.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }

    //分集详情
    public function vserialiDetails($id)
    {
        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('分集详情'));

            // if (Request::get('view') !== 'table') {
            //     $grid->view('admin.grid.card');
            // }
            // $content->body($this->vassetiGrid($id));

            // 分集详情
            $data = $this->serialDetailsData($id);
            $content->row(view('entity.asset.video.vseriali.details', $data));

            // 分集数据
            $content->row($this->vserialiTab($id));
        });
    }

    //分集详情的数据
    public function serialDetailsData($id)
    {
        $data            = [];
        $vserialiDetails = Vseriali::where('id', '=', $id)->with('vifiles', 'vposteris')->first();

        // 文件
        $vifiles = '';
        if ($vifiles = $vserialiDetails->vifiles) {
            $vifiles = $vserialiDetails->vifiles->pluck('name')->implode(',');
        }
        // 文件
        $data['vifiles'] = $vifiles;
        // 分集编号
        $data['vseriali_no'] = $vserialiDetails->vseriali_no;
        // 分集名称
        $data['name'] = $vserialiDetails->name;
        // 标题
        $data['title'] = $vserialiDetails->title;
        // 副标题
        $data['subtitle'] = $vserialiDetails->subtitle;
        // 第几集
        $data['episode'] = $vserialiDetails->episode;
        // 评分
        $data['score'] = $vserialiDetails->score;
        // 首播时间
        $data['firstdate'] = date('Y-m-d', strtotime($vserialiDetails->firstdate)); // $vserialiDetails->firstdate;
        // 上线时间
        $data['online_at'] = date('Y-m-d', strtotime($vserialiDetails->online_at)); // $vserialiDetails->online_at;
        // 下线时间
        $data['offline_at'] = date('Y-m-d', strtotime($vserialiDetails->offline_at)); // $vserialiDetails->offline_at;
        // 简介
        $data['short_desc'] = $vserialiDetails->short_desc;
        // 详情
        $data['long_desc'] = $vserialiDetails->long_desc;
        return $data;
    }

    // 分集tab
    public function vserialiTab($id)
    {
        $tab = new Tab();
        $tab->add('文件信息', $this->vifileGrid($id));
        $tab->add('图片信息', $this->vposteriGrid($id));
        return $tab;
    }

    // 文件信息
    public function vifileGrid($id)
    {
        return Admin::grid(Vifile::class, function (Grid $grid) use ($id) {

            // 如果分集已经上线且发布,则不让新增、编辑、删除操作
            $data = Vseriali::where('id', '=', $id)->select(['online_status', 'publish_status'])->first();

            if ($data && $data->online_status == 1 && $data->publish_status == 1) {
                // 禁用行操作列
                $grid->disableActions();
                // 禁用创建按钮
                $grid->disableCreation();
            }

            // 文件数据
            $vifiles = Vseriali::find($id)->vifiles->toArray();
            $grid->model()->whereIn('id', array_column($vifiles, 'id'));
            $grid->column('id', 'ID')->sortable();
            $grid->column('sp.name', '服务商')->sortable();
            $grid->column('resolution.name', '清晰度')->sortable();
            $grid->column('vfileext.name', '文件扩展名')->sortable();
            $grid->column('title', '标题')->sortable();
            $grid->column('subtitle', '副标题')->sortable();
            $grid->column('name', '名称')->sortable();
            $grid->column('path', '文件路径')->sortable();
            $grid->column('size', '文件大小(M)')->sortable();
            $grid->column('md5', '文件MD5')->sortable();
            $grid->column('duration', '时长')->sortable();
            $grid->column('href', '下载路径')->sortable();
            $grid->column('type', '文件类型')->display(function ($val) {
                switch ($val) {
                    case 1:
                        return '正片';
                        break;
                    case 2:
                        return '片花';
                        break;
                    case 3:
                        return '预告';
                        break;
                    default:
                        return '其他';
                        break;
                }
            });
            $grid->column('short_desc', '简述')->sortable();
            $grid->column('listorder', '排序')->sortable();

            // 禁用批量删除按钮
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    $batch->disableDelete();
                });
            });

            // 修改新建, 编辑, 删除按钮的路径
            // $grid->resource(route('entity.asset.video.media.vifiles.index'));
            $grid->resource(route('entity.asset.video.media.vifiles.vseriali.index', ['vseriali_id' => $id]));

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                $filter->disableIdFilter();

            });
        }, 'vifile');
    }

    // 图片信息
    public function vposteriGrid($id)
    {
        return Admin::grid(Vposteri::class, function (Grid $grid) use ($id) {

            $uploadConfig = config('custom.base.upload.vseriali');
            $driver       = $uploadConfig['driver'];
            $dir          = $uploadConfig['dir'];
            $uploadHosts  = config('custom.base.host');
            $host         = $uploadHosts[$driver];

            // 如果分集已经上线且发布,则不让新增、编辑、删除操作
            $data = Vseriali::where('id', '=', $id)->select(['online_status', 'publish_status'])->first();
            if ($data && $data->online_status == 1 && $data->publish_status == 1) {
                // 禁用行操作列
                $grid->disableActions();
                // 禁用创建按钮
                $grid->disableCreation();

                $flag = false;
            } else {
                $flag = true;
            }

            // 图片数据
            $vposteris = Vseriali::find($id)->vposteris->toArray();
            $grid->model()->whereIn('id', array_column($vposteris, 'id'));
            $grid->column('id', 'ID')->sortable();
            $grid->column('name', '名称')->sortable();
            $grid->column('title', '显示标题')->sortable();
            $grid->column('subtitle', '显示副标题')->sortable();
            $grid->column('vimgtag.name', '图片类型')->sortable();
            $grid->column('imgtpl.name', '图像规格')->sortable();
            $grid->column('href', '海报链接')->sortable();
            $grid->column('listorder', '排序')->sortable();

            // 批量操作
            $grid->tools(function ($tools) {
                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    $batch->disableDelete();
                });
            });

            // 修改新建, 编辑, 删除按钮的路径
            // $grid->resource(route('entity.asset.video.media.vposteris.index'));
            $grid->resource(route('entity.asset.video.media.vposteris.vseriali.index', ['vseriali_id' => $id]));

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                $filter->disableIdFilter();
            });

            $grid->tools(function ($tools) {
                $tools->append(new GridView());
            });

            if (\Illuminate\Support\Facades\Request::get('view') !== 'table') {
                $grid->view('admin.grid.card', ['image_column' => 'href', 'text_column' => 'title', 'server' => $host, 'flag' => $flag]);
            }
        }, 'vposteri');
    }

    /**
     * 剧集详情的分集crud
     */
    /**
     * [vassetiIndex description]
     * @param  [type] $vasseti_id [description]
     * @return [type]             [description]
     */
    public function vassetiIndex($vasseti_id)
    {
        return Admin::content(function (Content $content) {

            $content->header(__('entity.asset.video.vserialis.index_header'));
            $content->description(__('entity.asset.video.vserialis.index_description'));

            $content->body($this->grid());
        });
    }

    /**
     * 剧集的分集新建
     *
     * @return Response
     */
    public function vassetiCreate($vasseti_id)
    {
        // 如果媒资已经上线且发布,则不让新增、编辑、删除操作
        $data = Vasseti::where('id', '=', $vasseti_id)->select('online_status', 'publish_status')->first();

        if ($data && $data->online_status == 1 && $data->publish_status == 1) {

            Flash::error('该媒资已上线发布,不能添加分集');

            return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.asset.video.vassetis.vasseti_details', ['vasseti_id' => $vasseti_id]));
        }

        return Admin::content(function (Content $content) use ($vasseti_id) {

            $content->header(__('entity.asset.video.vserialis.create_header'));
            $content->description(__('entity.asset.video.vserialis.create_description'));

            $content->body($this->vassetiForm($vasseti_id));

        });
    }

    /**
     * Store a newly created Vseriali in storage.
     *
     * @param VposteriRequest $request
     *
     * @return Response
     */
    public function vassetiStore($vasseti_id, VserialiRequest $request)
    {
        // 如果媒资已经上线且发布,则不让新增、编辑、删除操作
        $data = Vasseti::where('id', '=', $vasseti_id)->select('online_status', 'publish_status')->first();

        if ($data && $data->online_status == 1 && $data->publish_status == 1) {

            Flash::error('该媒资已上线发布,不能添加分集');

            return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.asset.video.vassetis.vasseti_details', ['vasseti_id' => $vasseti_id]));
        }

        // 新建的时候和剧集关联
        if (!$vasseti = Vasseti::find($vasseti_id)) {
            Flash::error('剧集不能为空!');
            return redirect(route('entity.asset.video.vserialis.index'));
        }

        $input = $request->all();

        $vseriali = $this->vserialiRepository->create($input);

        $vasseti->vserialis()->save($vseriali);
        Flash::success(__('entity.asset.video.vserialis.saved_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.asset.video.vassetis.vasseti_details', ['vasseti_id' => $vasseti_id]));
    }

    /**
     * Show the form for editing the specified Vseriali.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function vassetiEdit($vasseti_id, $id)
    {
        // 如果媒资已经上线且发布,则不让新增、编辑、删除操作
        $data = Vasseti::where('id', '=', $vasseti_id)->select('online_status', 'publish_status')->first();

        if ($data && $data->online_status == 1 && $data->publish_status == 1) {

            Flash::error('该媒资已上线发布,不能修改分集');

            return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.asset.video.vassetis.vasseti_details', ['vasseti_id' => $vasseti_id]));
        }

        return Admin::content(function (Content $content) use ($id) {

            $content->header(__('entity.asset.video.vserialis.edit_header'));
            $content->description(__('entity.asset.video.vserialis.edit_description'));

            $content->body($this->vassetiForm()->edit($id));
        });
    }

    /**
     * Update the specified Vposteri in storage.
     *
     * @param  int              $id
     * @param VposteriRequest $request
     *
     * @return Response
     */
    public function vassetiUpdate($vasseti_id, $id, Request $request)
    {
        // 如果媒资已经上线且发布,则不让新增、编辑、删除操作
        $data = Vasseti::where('id', '=', $vasseti_id)->select('online_status', 'publish_status')->first();

        if ($data && $data->online_status == 1 && $data->publish_status == 1) {

            Flash::error('该媒资已上线发布,不能修改分集');

            return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.asset.video.vassetis.vasseti_details', ['vasseti_id' => $vasseti_id]));
        }

        $sValidators = [
            'vseriali_no' => 'required|unique:vserialis,vseriali_no,' . $id,
            'name'        => 'required|max:100',
            'title'       => 'max:100',
            'subtitle'    => 'max:100',
            'episode'     => 'required|numeric',
            'score'       => 'numeric',
            'vasseti_id'  => 'required',
            'firstdate'   => 'date',
            'online_at'   => 'date',
            'offline_at'  => 'date',
            'short_desc'  => 'required',
            'listorder'   => 'required|numeric',
        ];
        $validators = [];

        $input = $request->all();

        // 判断是否行内编辑
        $input = $this->handleEditable($input);

        // 动态判断校验
        foreach ($input as $key => $value) {
            if (isset($sValidators[$key])) {
                $validators[$key] = $sValidators[$key];
            }
        }
        // 定义校验, 没有移到request
        $validator = Validator::make($input, $validators, [
            // 'required' => ':attribute 不能为空',
        ], [
            'vseriali_no' => '分集编号',
            'name'        => '名称',
            'title'       => '标题',
            'subtitle'    => '副标题',
            'episode'     => '第几集',
            'score'       => '评分',
            'vasseti_id'  => '剧集',
            'firstdate'   => '首播时间',
            'online_at'   => '上线时间',
            'offline_at'  => '下线时间',
            'short_desc'  => '描述',
        ]
        );

        // 校验
        if ($validator->fails()) {
            return back()->withErrors($validator)->withInput();
        }

        $vseriali = $this->vserialiRepository->findWithoutFail($id);

        if (empty($vseriali)) {
            Flash::error(__('entity.asset.video.vserialis.not_found'));

            return redirect(route('entity.asset.video.vserialis.index'));
        }

        $vseriali = $this->vserialiRepository->update($input, $id);

        if ($vseriali) {
            if (is_array($request->get('vposteris'))) {
                $vseriali->vposteris()->sync(array_filter($request->get('vposteris')));
            }
            if (is_array($request->get('vifiles'))) {
                $vseriali->vifiles()->sync(array_filter($request->get('vifiles')));
            }
        }

        Flash::success(__('entity.asset.video.vserialis.updated_success'));

        return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.asset.video.vassetis.vasseti_details', ['vasseti_id' => $vasseti_id]));
    }

    public function vassetiDestroy($vasseti_id, $id)
    {
        // 如果媒资已经上线且发布,则不让新增、编辑、删除操作
        $data = Vasseti::where('id', '=', $vasseti_id)->select('online_status', 'publish_status')->first();

        if ($data && $data->online_status == 1 && $data->publish_status == 1) {

            Flash::error('该媒资已上线发布,不能删除分集');

            return Input::get('_previous_') ? redirect(Input::get('_previous_')) : redirect(route('entity.asset.video.vassetis.vasseti_details', ['vasseti_id' => $vasseti_id]));
        }

        // 根据 `,` 判断传递过来的是单个id还是多个id
        if (substr_count($id, ',') >= 1) {
            $id = explode(",", $id);
        }

        // 如果是数组则进行批量删除
        if (is_array($id)) {
            if ($flag = $this->vserialiRepository->batchDelete('id', $id)) {
                return response()->json(['message' => __('entity.asset.video.vserialis.deleted_success'), 'status' => $flag]);
            } else {
                return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
            }
        }

        $vseriali = $this->vserialiRepository->findWithoutFail($id);

        if (empty($vseriali)) {
            Flash::error(__('entity.asset.video.vserialis.not_found'));

            return redirect(route('entity.asset.video.vserialis.index'));
        }

        if ($flag = $this->vserialiRepository->delete($id)) {
            // 删除图片
            $vseriali->vposteris()->detach();
            // 文件
            $vseriali->vifiles()->detach();
            return response()->json(['message' => __('entity.asset.video.vserialis.deleted_success'), 'status' => $flag]);
        } else {
            return response()->json(['message' => __('base.deleted.error'), 'status' => $flag]);
        }
    }
    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function vassetiForm($vasseti_id)
    {
        return Admin::form(Vseriali::class, function (Form $form) use ($vasseti_id) {

            $form->display('id', 'ID');
            $form->text('vseriali_no', '分集编号');
            $vifiles = Vifile::pluck('name', 'id');
            $form->multipleSelect('vifiles', '分集文件')->options($vifiles);
            $form->text('name', '分集名称');
            $form->text('title', '标题');
            $form->text('subtitle', '副标题');
            $form->number('episode', '第几集');
            $form->number('score', '分集评分');
            // $form->date('firstdate', '首播日期')->format('YYYY-MM-DD');
            // $form->date('online_at', '上线日期')->format('YYYY-MM-DD');
            // $form->date('offline_at', '下线日期')->format('YYYY-MM-DD');
            $form->date('firstdate', '首播日期');
            $form->date('online_at', '上线日期');
            $form->date('offline_at', '下线日期');
            // 新增图片
            $vposteris = Vposteri::pluck('name', 'id');
            $form->multipleSelect('vposteris', '图片')->options($vposteris);
            $form->textarea('short_desc', '简介');
            $form->textarea('long_desc', '详述');

            $form->hidden('vasseti_id', '剧集')->default($vasseti_id);
            $form->number('listorder', '排序');
            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [addVasseti description]
     * @param Request $request [description]
     */
    public function selectVasseti(Request $request)
    {

        $vasseti = $request->get('q');

        return Vasseti::where('name', 'like', "%$vasseti%")->where('vasseti_type', '=', 1)->paginate(null, ['id', 'name as text']);
    }

    /**
     * [form description]
     * @return {[type]} [description]
     */
    protected function form()
    {
        return Admin::form(Vseriali::class, function (Form $form) {

            $form->display('id', 'ID');
            $form->text('vseriali_no', '分集编号')->help('必填');
            $vifiles = Vifile::pluck('name', 'id');
            $form->multipleSelect('vifiles', '分集文件')->options($vifiles);
            $form->text('name', '分集名称')->help('必填');
            $form->text('title', '标题');
            $form->text('subtitle', '副标题');
            $form->number('episode', '第几集');
            $form->number('score', '分集评分');
            // $form->date('firstdate', '首播日期')->format('YYYY-MM-DD');
            // $form->date('online_at', '上线日期')->format('YYYY-MM-DD');
            // $form->date('offline_at', '下线日期')->format('YYYY-MM-DD');
            $form->date('firstdate', '首播日期')->default(date('Y-m-d',time()))->help('必填');
            $form->date('online_at', '上线日期')->default(date('Y-m-d',time()))->help('必填');
            $form->date('offline_at', '下线日期')->default(date('Y-m-d',time()))->help('必填');
            // 新增图片
            $vposteris = Vposteri::pluck('name', 'id');
            $form->multipleSelect('vposteris', '图片')->options($vposteris);
            $form->textarea('short_desc', '简介')->help('必填');
            $form->textarea('long_desc', '详述');
            $vassetis = Vasseti::pluck('name', 'id');
            $form->select('vasseti_id', '剧集')->options($vassetis);
            // // $vassetis = Vasseti::pluck('name', 'id');
            // $form->select('vasseti_id', '剧集')->options(function ($id) {
            //     $vasseti = Vasseti::find($id);
            //     if ($vasseti) {
            //         return [$vasseti->id => $vasseti->name];
            //     }
            // })->ajax(route('entity.asset.video.vserialis.vassetis'))->help('必填');
            $form->number('listorder', '排序');
            // $form->display('created_at', __('base.created_at'));
            // $form->display('updated_at', __('base.updated_at'));

        });
    }

    /**
     * [grid description]
     * @return {[type]} [description]
     */
    protected function grid(Request $request)
    {

        return Admin::grid(Vseriali::class, function (Grid $grid) use ($request) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');

            // 状态过滤
            Publication::statusFilter($request->input('status'), $request->input('published'), $grid);


            // 表格中的按钮, 新增分集详情
            $grid->actions(function ($actions) {
                $publish_down_status = $actions->row->publish_down_status;
                $publish_status      = $actions->row->publish_status;
                $online_status       = $actions->row->online_status;
                $async_result        = $actions->row->async_result;
                $id                  = $actions->getKey();
                // 编辑媒资
                // if ($publish_down_status === 1 && $online_status === 0 && Admin::user()->can('entity.asset.video.vserialis.vseriali_details')) {
                $url = route('entity.asset.video.vserialis.vseriali_details', ['vseriali_id' => $id]);
                $actions->prepend('<a href ="' . $url . '" title="分集详情"><i class="fa fa-list"></i></a>');
                // }
                // 上线按钮
                // if ($publish_down_status === 1 && $online_status === 0 && Admin::user()->can('entity.asset.video.vserialis.up')) {
                //     $url      = route('entity.asset.video.vserialis.up');
                //     $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'up',_token: LA.token})";
                //     $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="上线"><i class="fa fa-arrow-up"></i></a>');
                // }
                // // 下线按钮
                // if ($online_status === 1 && Admin::user()->can('entity.asset.video.vserialis.down')) {
                //     $url      = route('entity.asset.video.vserialis.down');
                //     $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'down',_token: LA.token})";
                //     $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="下线"><i class="fa fa-arrow-down"></i></a>');
                // }
                // // 上线发布按钮
                // if ($online_status === 1 && $publish_status === 0 && $async_result === 1 && Admin::user()->can('entity.asset.video.vserialis.publish_one')) {
                //     $url      = route('entity.asset.video.vserialis.publish_one');
                //     $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'publish',_token: LA.token})";
                //     $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="上线发布"><i class="fa fa-cloud-upload"></i></a>');
                // }
                // // 下线发布按钮
                // if ($online_status === 0 && $publish_down_status === 0 && Admin::user()->can('entity.asset.video.vserialis.publish_down_one')) {
                //     $url      = route('entity.asset.video.vserialis.publish_down_one');
                //     $function = "upAndDownByOne('$url', 'post', {ids: [$id],action: 'publishDown',_token: LA.token})";
                //     $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="下线发布"><i class="fa fa-cloud-download"></i></a>');
                // }
                // 编辑按钮
                if (Admin::user()->cannot('entity.asset.video.vserialis.edit')) {
                    $actions->disableEdit();
                }

                // 删除按钮
                if (Admin::user()->cannot('entity.asset.video.vserialis.destroy')) {
                    $actions->disableDelete();
                }
                // // 只有状态下线的资源才可以编辑
                // if ($publish_down_status === 0) {
                //     $actions->disableEdit();
                //     // $actions->disableDelete();
                // }
                // // 上线发布后不能删除
                // if ($publish_status === 1){
                //     $actions->disableDelete();
                // }
            });

            // 添加按钮
            if (Admin::user()->cannot('entity.asset.video.vserialis.create')) {
                $grid->disableCreation();
            }

            // 导出按钮
            if (Admin::user()->cannot('entity.asset.video.vserialis.export')) {
                $grid->disableExport();
            }

            // 批量操作
            $grid->tools(function ($tools) {
                $url2 = route('entity.asset.video.vserialis.progress');
                // // 下线发布功能
                // if (Admin::user()->can('entity.asset.video.vserialis.publish_down')) {
                //     $url      = route('entity.asset.video.vserialis.publish_down');
                //     $function = "upAndDownByAll('$url', '$url2', 'get')";
                //     $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-info pull-right" style="margin-right: 10px"> <i class="fa fa-cloud-download"></i>下线发布</a>');
                // }
                // // 上线发布功能
                // if (Admin::user()->can('entity.asset.video.vserialis.publish')) {
                //     $url      = route('entity.asset.video.vserialis.publish');
                //     $function = "upAndDownByAll('$url', '$url2', 'get')";
                //     $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-info pull-right" style="margin-right: 10px"> <i class="fa fa-cloud-upload"></i>上线发布</a>');
                // }
                // // 全部下线功能
                // if (Admin::user()->can('entity.asset.video.vserialis.all_down')) {
                //     $url      = route('entity.asset.video.vserialis.all_down');
                //     $function = "upAndDownByAll('$url', '$url2', 'get')";
                //     $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-danger pull-right" style="margin-right: 10px"> <i class="fa fa-arrow-down"></i>全部下线</a>');
                // }
                // // 全部上线功能
                // if (Admin::user()->can('entity.asset.video.vserialis.all_up')) {
                //     $url      = route('entity.asset.video.vserialis.all_up');
                //     $function = "upAndDownByAll('$url', '$url2', 'get')";
                //     $tools->append('<a href="javascript:void(0)" onclick="' . $function . '" class="btn btn-sm btn-success pull-right" style="margin-right: 10px"> <i class="fa fa-arrow-up"></i>全部上线</a>');
                // }

                // 过滤按钮
                // $tools->append(new \App\Admin\Extensions\Tools\Vseriali\VserialiStatus());
                // $tools->append(new \App\Admin\Extensions\Tools\Vseriali\VserialiPublished());
                // 批量按钮

                $url =  route('entity.assets.assets.model',['sp_no' => '','config_file_select'=>'']);
                $tools->append('<a href=' .$url. ' class="btn btn-sm btn-warning pull-right" title="导入数据"><i class="fa fa-ban"></i>导入数据</a>');

                $tools->batch(function ($batch) {
                    // 批量删除按钮
                    if (Admin::user()->cannot('entity.asset.video.vserialis.batch_destroy')) {
                        $batch->disableDelete();
                    }
                    // // 批量上线按钮
                    // if (Admin::user()->can('entity.asset.video.vserialis.up')) {
                    //     $batch->add('上线', new \App\Admin\Extensions\Tools\Vseriali\ReleaseVseriali('up'));
                    // }
                    // // 批量下线按钮
                    // if (Admin::user()->can('entity.asset.video.vserialis.down')) {
                    //     $batch->add('下线', new \App\Admin\Extensions\Tools\Vseriali\ReleaseVseriali('down'));
                    // }
                    // // 批量上线发布按钮
                    // if (Admin::user()->can('entity.asset.video.vserialis.publish_one')) {
                    //     $batch->add('上线发布', new \App\Admin\Extensions\Tools\Vseriali\ReleaseVseriali('publish'));
                    // }
                    // // 批量下线发布按钮
                    // if (Admin::user()->can('entity.asset.video.vserialis.publish_down_one')) {
                    //     $batch->add('下线发布', new \App\Admin\Extensions\Tools\Vseriali\ReleaseVseriali('publishDown'));
                    // }

                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('vseriali_no', '分集编号')->editable();
            $grid->column('vasseti.name', '剧集')->sortable();
            $grid->column('name', '分集名称')->editable();
            $grid->column('title', '标题')->editable();
            $grid->column('subtitle', '副标题')->sortable();
            $grid->column('episode', '第几集')->editable();
            $grid->column('score', '分集评分')->sortable()->editable();
            $grid->column('firstdate', '首播日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            // $grid->vifiles('文件')->pluck('name')->label();
            // $grid->vposteris('图片')->pluck('name')->label();
            // $grid->column('short_desc', '简介')->sortable();
            // $grid->column('long_desc', '详述')->sortable();
            $grid->column('listorder', '排序')->sortable()->editable();
            $grid->column('moderate_status', '编辑状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();

            $grid->column('online_status', '上线状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();
            $grid->column('publish_status', '发布状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                // $filter->disableIdFilter();
                // 剧集
                $filter->like('vasseti.name', '剧集');
                // 编号
                $filter->like('vseriali_no', '分集编号');
                // 名称
                $filter->like('name', '名称');
                // 标题
                $filter->like('title', '标题');
                // 副标题
                $filter->like('subtitle', '副标题');
                // 第几集
                $filter->like('episode', '第几集');
                // 首播时间
                $filter->between('firstdate', '首播时间')->datetime();
                // 上线时间
                $filter->between('online_at', '上线时间')->datetime();
                // 下线时间
                $filter->between('offline_at', '下线时间')->datetime();
            });
        });
    }


    protected function editor_grid(Request $request)
    {

        return Admin::grid(Vseriali::class, function (Grid $grid) use ($request) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');
            $grid->model()->where('moderate_status', '!=', 1);
            // 表格中的按钮, 新增分集详情
            $grid->actions(function ($actions) {
                $publish_down_status = $actions->row->publish_down_status;
                $publish_status      = $actions->row->publish_status;
                $online_status       = $actions->row->online_status;
                $async_result        = $actions->row->async_result;
                $id                  = $actions->getKey();
                //媒资详情
                if (Admin::user()->can('entity.asset.video.vserialis.vseriali_details')) {
                  $url = route('entity.asset.video.vserialis.vseriali_details', ['vseriali_id' => $id]);
                  $actions->prepend('<a href ="' . $url . '" title="分集详情"><i class="fa fa-list"></i></a>');
                }

                // 提交审核申请
                if ( Admin::user()->can('content_audit.content_audits.create.moderate')) {
                    $url      = route('entity.content_audit.content_audits.create.moderate');
                    $function = "upAndDownByOne('$url', 'post', {content_id: $id, content_model: 'vseriali',audit_type: 'moderate', _token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="提交媒资审核申请"><i class="fa fa-eye"></i></a>');
                }

                $actions->disableEdit();

                $actions->disableDelete();

            });

            $grid->disableCreation();

            $grid->disableExport();


            // 批量操作
            $grid->tools(function ($tools) {
                // 批量按钮
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('vseriali_no', '分集编号')->editable();
            $grid->column('vasseti.name', '剧集')->sortable();
            $grid->column('name', '分集名称')->editable();
            $grid->column('title', '标题')->editable();
            $grid->column('subtitle', '副标题')->sortable();
            $grid->column('episode', '第几集')->editable();
            $grid->column('score', '分集评分')->sortable()->editable();
            $grid->column('firstdate', '首播日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            // $grid->vifiles('文件')->pluck('name')->label();
            // $grid->vposteris('图片')->pluck('name')->label();
            // $grid->column('short_desc', '简介')->sortable();
            // $grid->column('long_desc', '详述')->sortable();
            $grid->column('listorder', '排序')->sortable()->editable();
            $grid->column('moderate_status', '编辑状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();

            $grid->column('online_status', '上线状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();
            $grid->column('publish_status', '发布状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                // $filter->disableIdFilter();
                // 剧集
                $filter->like('vasseti.name', '剧集');
                // 编号
                $filter->like('vseriali_no', '分集编号');
                // 名称
                $filter->like('name', '名称');
                // 标题
                $filter->like('title', '标题');
                // 副标题
                $filter->like('subtitle', '副标题');
                // 第几集
                $filter->like('episode', '第几集');

            });
        });
    }


    protected function online_grid(Request $request)
    {

        return Admin::grid(Vseriali::class, function (Grid $grid) use ($request) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');
            $grid->model()->where('online_status', '!=', 1)->where('moderate_status', '=', 3);
            // 表格中的按钮, 新增分集详情
            $grid->actions(function ($actions) {
                $publish_down_status = $actions->row->publish_down_status;
                $publish_status      = $actions->row->publish_status;
                $online_status       = $actions->row->online_status;
                $async_result        = $actions->row->async_result;
                $id                  = $actions->getKey();
                //媒资详情
                if (Admin::user()->can('entity.asset.video.vserialis.vseriali_details')) {
                    $url = route('entity.asset.video.vserialis.vseriali_details', ['vseriali_id' => $id]);
                    $actions->prepend('<a href ="' . $url . '" title="分集详情"><i class="fa fa-list"></i></a>');
                }

                // 提交审核申请
                if ( Admin::user()->can('content_audit.content_audits.create.online')) {
                    $url      = route('entity.content_audit.content_audits.create.online');
                    $function = "upAndDownByOne('$url', 'post', {content_id: $id, content_model: 'vseriali',audit_type: 'online', _token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="提交媒资上线申请"><i class="fa fa-eye"></i></a>');
                }

                $actions->disableEdit();

                $actions->disableDelete();

            });

            $grid->disableCreation();

            $grid->disableExport();


            // 批量操作
            $grid->tools(function ($tools) {
                // 批量按钮
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('vseriali_no', '分集编号')->editable();
            $grid->column('vasseti.name', '剧集')->sortable();
            $grid->column('name', '分集名称')->editable();
            $grid->column('title', '标题')->editable();
            $grid->column('subtitle', '副标题')->sortable();
            $grid->column('episode', '第几集')->editable();
            $grid->column('score', '分集评分')->sortable()->editable();
            $grid->column('firstdate', '首播日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            // $grid->vifiles('文件')->pluck('name')->label();
            // $grid->vposteris('图片')->pluck('name')->label();
            // $grid->column('short_desc', '简介')->sortable();
            // $grid->column('long_desc', '详述')->sortable();
            $grid->column('listorder', '排序')->sortable()->editable();
            $grid->column('moderate_status', '编辑状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();

            $grid->column('online_status', '上线状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();
            $grid->column('publish_status', '发布状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                // $filter->disableIdFilter();
                // 剧集
                $filter->like('vasseti.name', '剧集');
                // 编号
                $filter->like('vseriali_no', '分集编号');
                // 名称
                $filter->like('name', '名称');
                // 标题
                $filter->like('title', '标题');
                // 副标题
                $filter->like('subtitle', '副标题');
                // 第几集
                $filter->like('episode', '第几集');

            });
        });
    }


    protected function publish_grid(Request $request)
    {

        return Admin::grid(Vseriali::class, function (Grid $grid) use ($request) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');
            $grid->model()->where('publish_status', '!=', 1)
                          ->where('online_status', '=', 3)
                          ->where('moderate_status', '=', 3);
            // 表格中的按钮, 新增分集详情
            $grid->actions(function ($actions) {
                $publish_down_status = $actions->row->publish_down_status;
                $publish_status      = $actions->row->publish_status;
                $online_status       = $actions->row->online_status;
                $async_result        = $actions->row->async_result;
                $id                  = $actions->getKey();
                //媒资详情
                if (Admin::user()->can('entity.asset.video.vserialis.vseriali_details')) {
                    $url = route('entity.asset.video.vserialis.vseriali_details', ['vseriali_id' => $id]);
                    $actions->prepend('<a href ="' . $url . '" title="分集详情"><i class="fa fa-list"></i></a>');
                }

                // 提交审核申请
                if ( Admin::user()->can('content_audit.content_audits.create.publish')) {
                    $url      = route('entity.content_audit.content_audits.create.publish');
                    $function = "upAndDownByOne('$url', 'post', {content_id: $id, content_model: 'vseriali',audit_type: 'publish', _token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="提交媒资上线申请"><i class="fa fa-eye"></i></a>');
                }

                $actions->disableEdit();

                $actions->disableDelete();

            });

            $grid->disableCreation();

            $grid->disableExport();


            // 批量操作
            $grid->tools(function ($tools) {
                // 批量按钮
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('vseriali_no', '分集编号')->editable();
            $grid->column('vasseti.name', '剧集')->sortable();
            $grid->column('name', '分集名称')->editable();
            $grid->column('title', '标题')->editable();
            $grid->column('subtitle', '副标题')->sortable();
            $grid->column('episode', '第几集')->editable();
            $grid->column('score', '分集评分')->sortable()->editable();
            $grid->column('firstdate', '首播日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            // $grid->vifiles('文件')->pluck('name')->label();
            // $grid->vposteris('图片')->pluck('name')->label();
            // $grid->column('short_desc', '简介')->sortable();
            // $grid->column('long_desc', '详述')->sortable();
            $grid->column('listorder', '排序')->sortable()->editable();
            $grid->column('moderate_status', '编辑状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();

            $grid->column('online_status', '上线状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();
            $grid->column('publish_status', '发布状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                // $filter->disableIdFilter();
                // 剧集
                $filter->like('vasseti.name', '剧集');
                // 编号
                $filter->like('vseriali_no', '分集编号');
                // 名称
                $filter->like('name', '名称');
                // 标题
                $filter->like('title', '标题');
                // 副标题
                $filter->like('subtitle', '副标题');
                // 第几集
                $filter->like('episode', '第几集');

            });
        });
    }


    protected function offline_grid(Request $request)
    {
        return Admin::grid(Vseriali::class, function (Grid $grid) use ($request) {
            // 考虑是否需要scope和排序
            // $grid->model()->orderBy('listorder', 'asc');
            $grid->model()->where('online_status', '=', 3);
            // 表格中的按钮, 新增分集详情
            $grid->actions(function ($actions) {
                $publish_down_status = $actions->row->publish_down_status;
                $publish_status      = $actions->row->publish_status;
                $online_status       = $actions->row->online_status;
                $async_result        = $actions->row->async_result;
                $id                  = $actions->getKey();
                //媒资详情
                if (Admin::user()->can('entity.asset.video.vserialis.vseriali_details')) {
                    $url = route('entity.asset.video.vserialis.vseriali_details', ['vseriali_id' => $id]);
                    $actions->prepend('<a href ="' . $url . '" title="分集详情"><i class="fa fa-list"></i></a>');
                }

                // 提交审核申请
                if ( Admin::user()->can('content_audit.content_audits.create.offline')) {
                    $url      = route('entity.content_audit.content_audits.create.offline');
                    $function = "upAndDownByOne('$url', 'post', {content_id: $id, content_model: 'vseriali',audit_type: 'offline', _token: LA.token})";
                    $actions->append('<a href="javascript:void(0)" onclick="' . $function . '" title="提交媒资上线申请"><i class="fa fa-eye"></i></a>');
                }

                $actions->disableEdit();

                $actions->disableDelete();

            });

            $grid->disableCreation();

            $grid->disableExport();


            // 批量操作
            $grid->tools(function ($tools) {
                // 批量按钮
                $tools->batch(function ($batch) {
                    $batch->disableDelete();
                });
            });

            $grid->column('id', 'ID')->sortable();
            $grid->column('vseriali_no', '分集编号')->editable();
            $grid->column('vasseti.name', '剧集')->sortable();
            $grid->column('name', '分集名称')->editable();
            $grid->column('title', '标题')->editable();
            $grid->column('subtitle', '副标题')->sortable();
            $grid->column('episode', '第几集')->editable();
            $grid->column('score', '分集评分')->sortable()->editable();
            $grid->column('firstdate', '首播日期')->display(function ($val) {
                if ($val) {
                    return date('Y-m-d', strtotime($val));
                }
                return '';
            })->sortable();
            // $grid->vifiles('文件')->pluck('name')->label();
            // $grid->vposteris('图片')->pluck('name')->label();
            // $grid->column('short_desc', '简介')->sortable();
            // $grid->column('long_desc', '详述')->sortable();
            $grid->column('listorder', '排序')->sortable()->editable();
            $grid->column('moderate_status', '编辑状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();

            $grid->column('online_status', '上线状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();
            $grid->column('publish_status', '发布状态')->display(function ($val) {
                switch ($val) {
                    case 0:
                        return '<span class="badge bg-blue">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 1:
                        return '<span class="badge bg-yellow">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 2:
                        return '<span class="badge bg-red">'.content_audit::$audit_status[$val].'</span>';
                        break;
                    case 3:
                        return '<span class="badge bg-green">'.content_audit::$audit_status[$val].'</span>';
                        break;
                }
            })->sortable();

            /**
             * 过滤处理
             */
            $grid->filter(function ($filter) {
                // 禁用id查询框
                // $filter->disableIdFilter();
                // 剧集
                $filter->like('vasseti.name', '剧集');
                // 编号
                $filter->like('vseriali_no', '分集编号');
                // 名称
                $filter->like('name', '名称');
                // 标题
                $filter->like('title', '标题');
                // 副标题
                $filter->like('subtitle', '副标题');
                // 第几集
                $filter->like('episode', '第几集');

            });
        });
    }

    /**
     * 全部上线功能
     */
    public function allUp()
    {
        if (Admin::user()->cannot('entity.asset.video.vserialis.all_up')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Vseriali::where(['online_status' => 0, 'publish_down_status' => 1])->count();
        $result = Publication::getTotalNum(new Vseriali(), [
            [['online_status' => 0], 'ID为以下分集已经上线: '],
            [['publish_down_status' => 1], 'ID为以下分集还未下线发布: '],
        ], '分集上线');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data = ['task_type' => '分集上线', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        dispatch(new VserialiJob(['dispatch', 'up'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 全部下线功能
     */
    public function allDown()
    {
        if (Admin::user()->cannot('entity.asset.video.vserialis.all_down')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Vseriali::where(['online_status' => 1])->count();
        $result = Publication::getTotalNum(new Vseriali(), [
            [['online_status' => 1], 'ID为以下分集还没上线'],
        ], '分集下线');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data = ['task_type' => '分集下线', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        $taskid = Publication::insertTasks($data);
        dispatch(new VserialiJob(['dispatch', 'down'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }
 
    /**
     * 发布功能,由于是全部发布,整个操作放入队列
     */
    public static function publish(Request $request)
    {
        if (Admin::user()->cannot('entity.asset.video.vserialis.publish')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Vseriali::where(['online_status' => 1, 'publish_status' => 0, 'async_result' => 1])->count();
        $result = Publication::getTotalNum(new Vseriali(), [
            [['online_status' => 1], 'ID为以下分集还未上线: '],
            [['publish_status' => 0], 'ID为以下分集已经上线发布: '],
            [['async_result' => 1], 'ID为以下分集还未注入: '],
        ], '分集发布');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data = ['task_type' => '分集发布', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        // 任务表插入一条记录
        $taskid = Publication::insertTasks($data);
        dispatch(new VserialiJob(['dispatch', 'publish'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }
  
    /**
     * 下线发布功能
     */
    public function publishDown(Request $request)
    {
        if (Admin::user()->cannot('entity.asset.video.vserialis.publish_down')) {
            return response()->json(['taskid' => 0, 'content' => '您的权限不够!']);
        }
        // 统计需要处理的任务的总数
        // $total_num = Vseriali::where(['online_status' => 0, 'publish_down_status' => 0])->count();
        $result = Publication::getTotalNum(new Vseriali(), [
            [['online_status' => 0], 'ID为以下分集还未下线: '], 
            [['publish_down_status' => 0], 'ID为以下分集已经下线发布: '],
        ], '分集下线发布');
        list($total_num, $content) = $result;
        if (!$total_num) {
            return response()->json(['taskid' => 0, 'content' => $content]);
        }
        $data = ['task_type' => '分集下线发布', 'user_id' => Admin::user()->id, 'total_num' => $total_num];
        // 任务表插入一条记录
        $taskid = Publication::insertTasks($data);
        dispatch(new VserialiJob(['dispatch', 'publishDown'], '', $taskid));
        return response()->json(['taskid' => $taskid, 'content' => $content]);
    }

    /**
     * 单个,批量上下线功能,单个,单个发布功能
     */
    public function batchModerate(Request $request)
    {
        $user_id = Admin::user()->id;
        switch ($request->action) {
            // 上线
            case 'up':
                if (Admin::user()->cannot('entity.asset.video.vserialis.up')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // 过滤ids
                $result = Publication::myfilter(new Vseriali(), $request->ids, [
                    [['online_status' => 0], 'ID为以下分集已经上线: '],
                    [['publish_down_status' => 1], 'ID为以下分集还未下线发布: '],
                ], '分集上线');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                $result = Publication::updateMany(new Vseriali(), $ids, [
                    'online_status'       => 1,
                    'publish_down_status' => 0,
                    'user_id'             => $user_id,
                    'online_at'           => date('Y-m-d H:i:s'),
                ]);
                return response()->json(['status' => 'success', 'content' => $result ? $content : '上线操作失败']);
            // 发布
            case 'publish':
                if (Admin::user()->cannot('entity.asset.video.vserialis.publish')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                $result = Publication::myfilter(new Vseriali(), $request->ids, [
                    [['online_status' => 1], 'ID为以下分集还未上线: '],
                    [['publish_status' => 0], 'ID为以下分集已经上线发布: '],
                    [['async_result' => 1], 'ID为以下分集还未注入: '],
                ], '分集发布');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                // 如果是批量放入队列中处理
                if (count($ids) > 1) {
                    $data = ['task_type' => '分集发布', 'user_id' => $user_id, 'total_num' => count($ids)];
                    $taskid = Publication::insertTasks($data);
                    dispatch(new VserialiJob(['publish'], $ids, $taskid));
                    $url = route('entity.asset.video.vserialis.progress');
                    return response()->json(['status' => 'queue', 'content' => $content, 'taskid' => $taskid, 'url' => $url]);
                }
                // 如果是单条数据发布
                $vserialis = Vseriali::with(['vposteris', 'vifiles'])->whereIn('id', $ids)->get();
                $vseriali_datas = VserialiJob::makeVserialis($vserialis);
                $result1 = Publication::insertApi('vserialis', $vseriali_datas);
                $result2 = Publication::updateMany(new Vseriali(), $ids, [
                    'publish_status' => 1,
                    'user_id'        => $user_id,
                ]);
                $content = ($result1 && $result2) ? $content : '上线发布失败!';
                return response()->json(['status' => 'success', 'content' => $content]);
            // 下线
            case 'down':
                if (Admin::user()->cannot('entity.asset.video.vserialis.down')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                $result = Publication::myfilter(new Vseriali(), $request->ids, [
                    [['online_status' => 1], 'ID为以下分集还没上线'],
                    [[['async_result' , '<>', 0]], 'ID为以下分集正在注入'],
                ], '分集下线');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                $result = Publication::updateMany(new Vseriali(), $ids, [
                    'online_status'  => 0,
                    'publish_status' => 0,
                    'user_id'        => $user_id,
                    'offline_at'     => date('Y-m-d H:i:s'),
                ]);
                return response()->json(['status' => 'success', 'content' => $result ? $content : '下线操作失败']);
            // 下线发布
            case 'publishDown':
                if (Admin::user()->cannot('entity.asset.video.vserialis.publish_one')) {
                    return response()->json(['status' => 'error', 'content' => '您的权限不够!']);
                }
                // $ids = Publication::myfilter(new Vseriali(), $request->ids, ['online_status' => 0, 'publish_down_status' => 0]);
                $result = Publication::myfilter(new Vseriali(), $request->ids, [
                    [['online_status' => 0], 'ID为以下分集还未下线: '], 
                    [['publish_down_status' => 0], 'ID为以下分集已经下线发布: '],
                ], '分集下线发布');
                list($ids, $content) = $result;
                if (!$ids->first()) {
                    return response()->json(['status' => 'error', 'content' => $content]);
                }
                /*
                 * 删除接口库中对应的数据
                 * 这里有两种可能的情况
                 * 1.资源还没有上线发布就被下线, 接口库没有还没有这个资源
                 * 2.资源已经上线发布过, 接口库中有这个资源
                 * 所以在删除接口库中的数据时, 需要先判断接口库中是否有对应数据, 有则返回删除操作的结果, 没有则直接返回true
                 */
                $vserialisCount = DB::connection('interface')->table('vserialis')->whereIn('vseriali_id', $ids)->count();
                if ($vserialisCount) {
                    // 删除接口库中对应的数据
                    $result1 = Publication::deleteApi('vserialis', 'vseriali_id', $ids);
                } else {
                    $result1 = true;
                }
                // 更新状态
                $result2 = Publication::updateMany(new Vseriali(), $ids, [
                    'publish_down_status' => 1,
                    'user_id'             => $user_id,
                ]);
                return response()->json(['status' => 'success', 'content' => $result1 && $result2 ? $content : '下线发布失败!']);
        }
    }
   
    /**
     * 查询进度
     */
    public function queryProgress(Request $request)
    {
        $taskid = (int) $request->input('taskid');
        return Publication::progress($taskid);
    }
}
